<template>
  <el-dialog width="66%" :title="dialogTitle" v-model="dialogVisible" modal @close="closeDialog" draggable
    :close-on-click-modal="false" :append-to-body="true">
    <printPreview ref="printPreview" :tableData="tableData" :tableProps="tableProps" :printFrom="printFrom">
    </printPreview>
    <div>
      <el-form class="dialog-form" :model="formData" ref="vForm" label-position="right" label-width="120px"
        size="medium" @submit.native.prevent :rules="formRules" :disabled="formDisabled">
        <el-row>
          <el-col :span="8" v-if="isDown">
            <el-form-item label="预计归还日期" prop="planBackDate">
              <el-date-picker v-model="formData.planBackDate" type="date" style="width: 100%"
                :picker-options="pickerOptions" placeholder="请选择日期" value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="接收人" prop="recipient">
              <el-input v-model="formData.recipient" placeholder="请输入接收人" link clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="接收人电话" prop="recipientPhone">
              <el-input v-model="formData.recipientPhone" placeholder="请输入接收人电话" link clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="用途" prop="purpose">
              <el-input v-model="formData.purpose" placeholder="请输入用途" link clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <el-table :data="tableData" border style="width: 100%" max-height="30vh">
        <el-table-column v-for="item of tableProps" :key="item.props" :prop="item.prop" :label="item.title"
          :width="item.width">
          <template #default="scope">
            <span v-if="item.prop === 'positionId_dictText'">
              {{ scope.row.positionId_dictText || scope.row.positionName }}
            </span>
            <span v-else-if="item.prop === 'stageStatus'">
              <el-tag v-if="scope.row.stageStatus == 0">未上架</el-tag>
              <el-tag v-if="scope.row.stageStatus == 1" type="success">已上架</el-tag>
              <el-tag v-if="scope.row.stageStatus == 2" type="danger">已下架</el-tag>
            </span>
            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="60">
          <template slot-scope="{ row }">
            <el-popconfirm title="确定要删除吗？" @confirm="() => handleDel(row)">
              <el-button slot="reference" icon="el-icon-delete" link size="mini" class="danger_button">删除</el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
      <el-button type="primary" @click="printOutBill" size="mini">打印出库单</el-button>
      <el-button type="primary" @click="submitForm" size="mini">出 库</el-button>
    </div>
  </el-dialog>
</template>

<script>
import printPreview from '@/components/printPreview.vue'
import { archivesOut, boxOut } from '@/api/rfid/outBill'
import moment from 'moment'
export default {
  name: 'archivesOutDialog',
  components: {
    printPreview,
  },
  data() {
    return {
      printFrom: [],
      type: '',
      dialogTitle: '',
      dialogVisible: false,
      isDown: false,
      formData: {},
      formDisabled: false,
      formRules: {
        planBackDate: [{ required: true, message: '请选择预计归还日期', trigger: 'change' }],
        recipient: [{ required: true, message: '请输入接收人', trigger: 'blur' }],
        recipientPhone: [
          { required: true, message: '请输入接收人电话', trigger: 'blur' },
          { validator: this.validatePhone, trigger: 'blur' },
        ],
      },
      exceptionTypeOptions: [],
      tableData: [],
      tableProps: [
        { title: '档号', prop: 'archiveNo', width: '', checked: true },
        { title: '题名', prop: 'archiveName', width: '', checked: true },
        { title: 'RFID', prop: 'rfid', width: '', checked: true },
        { title: '存放位置', prop: 'positionId_dictText', width: '', checked: true },
        { title: '上架状态', prop: 'stageStatus', width: '', checked: true },
      ],
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24 * 3600 * 1000
        },
      },
    }
  },
  methods: {
    printOutBill() {
      this.printFrom = [
        {
          name: '名称',
          data: '档案出库单',
        },
        {
          name: '预计归还日期',
          data: this.formData.planBackDate,
        },
        {
          name: '接收人',
          data: this.formData.recipient,
        },
        {
          name: '接收电话',
          data: this.formData.recipientPhone,
        },
        {
          name: '用途',
          data: this.formData.purpose,
        },
      ]
      this.$refs.printPreview.open()
    },
    add(record) {
      // 判断record中的上架状态是否是已下架
      this.isDown = !record.some((item) => item.stageStatus === 2);
      this.tableData = record
      this.formDisabled = false
      this.dialogTitle = '添加到出库列表'
      // 先清空表单数据
      this.formData = {}
      this.dialogVisible = true
    },
    handleDel(row) {
      this.tableData = this.tableData.filter((item) => item.labelId !== row.labelId)
    },
    validatePhone(rule, value, callback) {
      const phoneReg = /^1[3-9]\d{9}$/ // 正则表达式匹配中国大陆11位手机号码
      if (!phoneReg.test(value)) {
        callback(new Error('请输入有效的11位手机号码'))
      } else {
        callback()
      }
    },
    submitForm() {
      this.$refs['vForm'].validate((valid) => {
        if (valid) {
          // 判断表格中是否还有数据
          if (this.tableData.length === 0) {
            this.$message.warning('出库列表不能为空')
            return
          }
          this.formData.planBackDate = moment(this.formData.planBackDate).format('YYYY-MM-DD')
          this.formData.dataSources = 0
          this.formData.labelIds = this.tableData.map((item) => item.labelId)
          archivesOut(this.formData)
            .then((res) => {
              if (res.data.code === 200) {
                this.$message.success('出库成功')
                this.closeDialog()

                this.$emit('ok', this.tableData)
                this.$emit('clearSelection')
                this.$emit('update-data')
                this.$emit('reloadTable')
              } else {
                this.$message.warning(res.data.message)
              }
            })
            .catch((err) => {
              this.$message.error(err)
            })
        }
      })
    },
    closeDialog() {
      this.$refs['vForm'].resetFields()
      this.dialogVisible = false
    },
  },
}
</script>

<style scoped lang="less">
.el-table {
  display: flex;
  flex-direction: column;
}

.el-table__header-wrapper {
  overflow: unset;
}
</style>
